package test.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁的应用
 * @author yachao.guo
 * @date 2019-06-27 15:39
 */

public class Cache<K, V> {

    final Map<K, V> map = new HashMap<>();
    final ReadWriteLock rwl = new ReentrantReadWriteLock();
    final Lock readLock = rwl.readLock();
    final Lock writeLock = rwl.writeLock();

    V get(K key) {
        V value = null;
        readLock.lock();
        try {
            value = map.get(key);
        } finally {
            readLock.unlock();
        }
        if (value != null) {
            return value;
        }
        writeLock.lock();
        try {
            //二次验证 别的线程可能已经查询过数据库
            value = map.get(key);
            if (value == null) {
                //查询数据库
                //  value = 赋值
                map.put(key, value);
            }
        } finally {
            writeLock.unlock();
        }
        return value;
    }

    V put(K key, V value) {
        writeLock.lock();
        try {
            return map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }
}
